package ro.ss.bb.deployer.invoker;

import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

/**
 * Replace with your class description.
 */
public class AntInvoker {
    
    public static final String CONFIG_FILES_PROPERTIES_TAG = "configFiles";
    public static final String TARGET_BUILD_WAR = "buildWar";
    public static final String TARGET_DEPLOY = "deployWar";
    public static final String MAIN_ANT = "main_ant.xml";
    
    // main Ant Project
    protected Project p = new Project();

    /**
     * default file name deploy_ant.xml
     */
    public AntInvoker() {
        initProject(MAIN_ANT, null);
    }

    /**
     * Custom ant file name
     * 
     * @param buildFile filename (path also)
     */
    public AntInvoker(String buildFile) {
        initProject(buildFile+".xml", null);
    }
    
    /**
     * Custom ant file name, custom props
     * 
     * @param buildFile filename (path also)
     */
    public AntInvoker(String buildFile, Map<String, String> params) {
        initProject(buildFile+".xml", params);
    }

    protected void initProject(String file, Map<String, String> params) {
        File buildFile = new File(file);
        p.setUserProperty("ant.file", buildFile.getAbsolutePath());
        p.init();
        ProjectHelper helper = ProjectHelper.getProjectHelper();
        p.addReference("ant.projectHelper", helper);
        helper.parse(p, buildFile);
        // setting logger
        setLogger(p);
        if(params!=null){
            for (Map.Entry<String,String> entry : params.entrySet()) {
                p.setProperty(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Makes a DefaultLogger and attaches it to the project, default output is
     * the concole
     * 
     * @param p
     *            The project
     */
    protected void setLogger(Project p) {
        DefaultLogger consoleLogger = new DefaultLogger();
        consoleLogger.setErrorPrintStream(System.err);
        consoleLogger.setOutputPrintStream(System.out);
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
        p.addBuildListener(consoleLogger);
    }

    public Project getP() {
        return p;
    }

    public void setP(Project p) {
        this.p = p;
    }
}
